package org.com.app.knock.fragment;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.com.app.knock.KnockApplication;
import org.com.app.knock.activity.FriendActivity;
import org.com.app.knock.view.LoadingView;
import org.com.app.knock.view.RegisterItemView;
import org.json.JSONArray;
import org.json.JSONObject;

import z.lib.base.Base64;
import z.lib.base.BaseAdapter;
import z.lib.base.BaseItem;
import z.lib.base.BaseServiceCallBack;
import z.lib.base.BaseUtils;
import z.lib.base.BaseUtils.API;
import z.lib.base.BaseView;
import z.lib.base.CommonAndroid;
import z.lib.base.LogUtils;
import z.lib.base.callback.RestClient.RequestMethod;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.net.Uri;
//import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.acv.libs.nbase.BaseFragment;
import com.app.lazyload.ImageLoader2;
import com.knock.app.R;

public class RegisterFragment extends BaseFragment implements AnimationListener {
	protected static final String TAG = "RegisterFragment";
	private View views;
	private LoadingView loading;
	public static ImageLoader2 imageLoader;
	GridView listView;
	private BaseAdapter baseAdapter;
	private String img_icon ="";
	public static String response_ = "";
	public static String countryCode = "";
	ImageView img_icon_set;
	public static int REQUEST_CODE_IMAGE = 99;
	private String avatarString = "";// base64 cua image avatar
	public RegisterFragment() {
		super();
	}

	@Override
	public void setUpFragment(View view) {
		response_ = "";
		countryCode = "";
		InputMethodManager keyboard = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        keyboard.hideSoftInputFromWindow(view.getWindowToken(), 0);
		this.views = view;
		imageLoader = new ImageLoader2(getActivity());
		loading = CommonAndroid.getView(view, R.id.loading);
		listView =(GridView) views.findViewById(R.id.gridView_item);
		img_icon_set = (ImageView) views.findViewById(R.id.img_icon);
		CommonAndroid.getView(view, R.id.btn_back).setOnClickListener(this);
		CommonAndroid.getView(view, R.id.register).setOnClickListener(this);
//		CommonAndroid.getView(view, R.id.register_value4).setOnClickListener(this);
		CommonAndroid.getView(view, R.id.gallery).setOnClickListener(this);
		onLoadIcon();
	}
	
	@Override
	public void onResume(){
		super.onResume();
		if(!"".equals(countryCode)){
			TextView reg_value4 = CommonAndroid.getView(views, R.id.register_value4);
			reg_value4.setText(countryCode);
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		LogUtils.e("sssssssss","avatarString1111==" + avatarString);
		super.onActivityResult(requestCode, resultCode, data);
		try {
			if (requestCode == REQUEST_CODE_IMAGE && data.getData() != null) {
				try {
					Uri uriImage = data.getData();

					Bitmap bmp = null;
					try {
						bmp = decodeUri(getActivity(), uriImage, 350);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
//				bmp = getCroppedBitmap(bmp);
					bmp = imageLoader.getRoundedShape(bmp, 40);
					img_icon_set.setImageBitmap(bmp);
					avatarString = base64ImageToString(bmp);
					if(!"".equals(avatarString)){
						img_icon = "";
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				LogUtils.e("sssssssss","avatarString==" + avatarString);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static Bitmap decodeUri(Context c, Uri uri, final int requiredSize) throws FileNotFoundException {
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeStream(c.getContentResolver().openInputStream(uri), null, o);

		int width_tmp = o.outWidth, height_tmp = o.outHeight;
		int scale = 1;

		while (true) {
			if (width_tmp / 2 < requiredSize || height_tmp / 2 < requiredSize)
				break;
			width_tmp /= 2;
			height_tmp /= 2;
			scale *= 2;
		}

		BitmapFactory.Options o2 = new BitmapFactory.Options();
		o2.inSampleSize = scale;
		return BitmapFactory.decodeStream(c.getContentResolver().openInputStream(uri), null, o2);
	}
	
	/**
	 * this method crop image retangle to image circle
	 * 
	 * @param bitmap
	 * @return return new bitmap circle
	 */
	public Bitmap getCroppedBitmap(Bitmap bitmap) {
		Bitmap output = null;
		try {
			output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), android.graphics.Bitmap.Config.ARGB_8888);
			Canvas canvas = new Canvas(output);

			final int color = 0xff424242;
			final Paint paint = new Paint();
			final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());

			paint.setAntiAlias(true);
			canvas.drawARGB(0, 0, 0, 0);
			paint.setColor(color);
			canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 2, paint);
			paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
			canvas.drawBitmap(bitmap, rect, rect, paint);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return output;
	}
	
	private String base64ImageToString(Bitmap bmp){
//		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//		bmp.compress(Bitmap.CompressFormat.PNG, 90, byteArrayOutputStream);
//		byte[] byteArray = byteArrayOutputStream.toByteArray();
//		String encodeString = Base64.encodeToString(byteArray, Base64.DEFAULT);
		
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bmp.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
        byte [] byte_arr = stream.toByteArray();
        String image_str = "data:image/png;base64,"+ Base64.encodeBytes(byte_arr);
        
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        ImageIO.write(bmp, "png", baos);
//        byte[] res=baos.toByteArray();
//        String encodedImage = Base64.encodeBytes(baos.toByteArray());

		Log.i(TAG, "base64 avatar = " + image_str);
		return image_str;
	}

	private void onLoadIcon() {
		// TODO Auto-generated method stub
		HashMap<String, String> params = new HashMap<String, String>();
		BaseUtils.execute(getActivity(), RequestMethod.POST, API.API_DATA, params, callbackget);
	}
	
	private BaseServiceCallBack callbackget = new BaseServiceCallBack() {

		public void onStart() {
			CommonAndroid.showView(true, loading);
			CommonAndroid.hiddenKeyBoard(getActivity());
		};

		public void onError(String message) {
			CommonAndroid.showView(false, loading);
			if (!isFinish()) {
				LogUtils.e(TAG,"err=="+message);
			}
		};

		public void onSucces(String response) {
			CommonAndroid.showView(false, loading);
			if (!isFinish()) {
				response_ = response;
				JSONObject mainJsonObject;
				List<BaseItem> baseItems = new ArrayList<BaseItem>();
				baseItems.clear();
				try {
					mainJsonObject = new JSONObject(response);
					JSONArray array = mainJsonObject.getJSONObject("data").getJSONArray("avatars");
					for(int i =0; i < array.length();i++){
						baseItems.add(new BaseItem(array.getJSONObject(i)));
					}
					LogUtils.e(TAG,mainJsonObject.toString());
					addView(baseItems);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
	};
	
	protected void addView(List<BaseItem> baseItems) {
		// TODO Auto-generated method stub
		baseAdapter = new BaseAdapter(getActivity(), new ArrayList<Object>()) {
			@Override
			public BaseView getView(Context context, Object data) {
				final RegisterItemView sendItemView = new RegisterItemView(context);
				return sendItemView;
			}
		};
		baseAdapter.clear();
		baseAdapter.addAllItems(baseItems);
		baseAdapter.notifyDataSetChanged();
		listView.setOnItemClickListener(new OnItemClickListener() {
			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
//				BaseUtils.playMedia(getActivity(),R.raw.tap_message);
				BaseItem baseItem = (BaseItem) parent.getItemAtPosition(position);
				img_icon = baseItem.getString("id");
				String icon_url = baseItem.getString("url");
				imageLoader.DisplayImage(icon_url, img_icon_set);
				avatarString = "";
			}
		});
		listView.setAdapter(baseAdapter);
	}

	@Override
	public int layoytResurce() {
		return R.layout.register;
	}
	
	@Override
	public void onClick(View v) {
		super.onClick(v);
		int idView = v.getId();
		switch (idView) {
		case R.id.gallery:
			getAvatar();
			break;
		case R.id.btn_back:
			getActivity().finish();
			break;
		case R.id.register:
//			String name = CommonAndroid.getView(views, R.id.btn_back);
			TextView reg_value1 = CommonAndroid.getView(views, R.id.register_value1);
			String user_val1 = reg_value1.getText().toString().trim();
			TextView reg_value2 = CommonAndroid.getView(views, R.id.register_value2);
			String user_val2 = reg_value2.getText().toString().trim();
			TextView reg_value3 = CommonAndroid.getView(views, R.id.register_value3);
			String user_val3 = reg_value3.getText().toString().trim();
			TextView reg_value4 = CommonAndroid.getView(views, R.id.register_value4);
			String user_val4 = reg_value4.getText().toString().trim();
			
			if(!"".equals(user_val1) && !"".equals(user_val2) && !"".equals(user_val3) && !"".equals(user_val4) ){
//				GcmBroadcastReceiver.addDevice(getActivity(), user_name);
				register(user_val1,user_val2,user_val3, user_val4);
			}else{
				BaseUtils.showDialog(getActivity(), "value not blank!" );
			}
			InputMethodManager keyboard = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            keyboard.hideSoftInputFromWindow(v.getWindowToken(), 0);
			break;
		/*case R.id.register_value4:
			Intent Page = new Intent(getActivity(), AreaActivity.class);
			getActivity().startActivityForResult(Page,0);
			break;*/
		default:
			break;
		}
	}

	/**
	 * this method pick image from album of device
	 */
	private void getAvatar() {
		Intent intentPickImage = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(intentPickImage, REQUEST_CODE_IMAGE);
	}
	
	private void register(String user_val1, String user_val2, String user_val3, String user_val4) {
		// TODO Auto-generated method stub
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("name", user_val1);
		params.put("password", user_val2);
		params.put("email", user_val3);
		params.put("area", user_val4);
		params.put("platform", "0");
		params.put("devicetoken", KnockApplication.token_device_gcm);
		BaseUtils.execute(getActivity(), RequestMethod.POST, API.API_USER_REGISTER, params, callback);
		
	}
	
	private BaseServiceCallBack callback = new BaseServiceCallBack() {

		public void onStart() {
			CommonAndroid.showView(true, loading);
			CommonAndroid.hiddenKeyBoard(getActivity());
		};

		public void onError(String message) {
			CommonAndroid.showView(false, loading);
			if (!isFinish()) {
				BaseUtils.showDialog(getActivity(), "" + message);
			}
		};

		public void onSucces(String response) {
			if (!isFinish()) {
				JSONObject mainJsonObject;
				try {
					mainJsonObject = new JSONObject(response);
					LogUtils.e(TAG,"done"+ mainJsonObject.toString());
					String message = CommonAndroid.getString(mainJsonObject,
							BaseUtils.KEY.err_msg);
//					BaseUtils.showDialog(getActivity(), "" + message);
					updateAvata();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		
	};

	private void updateAvata() {
		// TODO Auto-generated method stub
		HashMap<String, String> params = new HashMap<String, String>();
		if(!"".equals(avatarString)){
			params.put("avatar", avatarString);
		}else{
			params.put("avatar_id", img_icon);
		}
		LogUtils.e(TAG,"paramavata==" + params.toString());
		BaseUtils.execute(getActivity(), RequestMethod.POST, API.API_USER_SAVE, params, callbackupdate);
	};
	
	private BaseServiceCallBack callbackupdate = new BaseServiceCallBack() {

		public void onStart() {
			CommonAndroid.showView(true, loading);
			CommonAndroid.hiddenKeyBoard(getActivity());
		};

		public void onError(String message) {
			CommonAndroid.showView(false, loading);
			if (!isFinish()) {
				BaseUtils.showDialog(getActivity(), "" + message);
			}
		};

		public void onSucces(String response) {
			CommonAndroid.showView(false, loading);
			if (!isFinish()) {
				JSONObject mainJsonObject;
				try {
					mainJsonObject = new JSONObject(response);
					LogUtils.e(TAG,"doneupdate"+ mainJsonObject.toString());
					String message = CommonAndroid.getString(mainJsonObject,
							BaseUtils.KEY.err_msg);
//					BaseUtils.showDialog(getActivity(), "" + message);
					Intent Page = new Intent(getActivity(), FriendActivity.class);
					getActivity().startActivityForResult(Page,0); 
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		
	};

	@Override
	public void onAnimationStart(Animation animation) {

	}

	@Override
	public void onAnimationEnd(Animation animation) {
		mHandle.sendEmptyMessage(0);
	}

	@Override
	public void onAnimationRepeat(Animation animation) {

	}
}